package com.w1.security.handler;


import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.ProviderNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 *{@link ProviderManager#authenticate}
 * 源码：manager调用in内存，获取details数据库存的用户，在这里进行对比
 * 所以这里就是获取用户信息，进行处理，这里是访问外部接口，判断接口返回类型，决定Authentication.setAuthenticated（True/False）
 * 这一步的核心是判断的逻辑
 * 认证管理器
 * @author mingyifan
 * @date 2022-02-24 16:09
 */
@Component
public class AuthManager implements AuthenticationManager {

    private final AuthProvider authProvider;

    public AuthManager(AuthProvider authProvider) {
        this.authProvider = authProvider;
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Authentication result = authProvider.authenticate(authentication);
        if (Objects.nonNull(result)) {
            return result;
        }
        throw new ProviderNotFoundException("Authentication failed!");
    }
}

